//发货单管理
//杨帆

interface IOrderDeliverManagentViewModel extends IBaseViewModel<IOrderDeliverQueryTerms>{
    /**
     * ui-grid控制
     */
    gridOptions: uiGrid.IGridOptionsOf<carryOrderListResponse>;
    /**
     * 时间日期格式
     */
    dateFormat: "{format:'YYYY.MM.DD HH:mm'}";
    /**
     * 订单状态
     */
    orderStatusDropDown:ValueListItemResponse[];
    /**
     * 客服专员下拉
     */
    customerServiceDropDown:EmployeeListItemResponse[];
    /**
     * 车长下拉
     */
    carLengthDropDown:ValueListItemResponse[];
    /**
     * 合同状态下拉
     */
    contractStatusDropDown:ValueListItemResponse[];
    /**
     * 回单状态下拉
     */
    receiptStatusDropDown:ValueListItemResponse[];
    /**
     * 油卡状态下拉
     */
    oilCCardStatusDropDown:ValueListItemResponse[];
    /**
     * 调度专员
     */
    dispatchOfficerDropDown: EmployeeListItemResponse[];
    /**
     * 查看详情
     */
    orderDetail: (id:string)=> void;
    /**
     * 导出报表
     */
    excel: ()=> void;
    /**
     * 导出报表2
     */
    excel2: ()=> void;
    /**
     * 定位
     */
    location: ()=> void;
    /**
     * 定位轨迹点
     */
    track: ()=> void;
    /**
     * 查询
     */
    query:()=>void;
    
    /**
     * 定位
     */
    carLocation: boolean;
    /**
     * 列表高度
     */
    heightA:number;
    /**
     * 北斗定位
     */
    BDNPL:()=>void;

    
}
/**
 * 查询条件
 */
interface IOrderDeliverQueryTerms{
    /**
     * 订单编号
     */
    orderId:string;
    /**
     * 客户单位
     */
    clientName:string;
    /**
     * 线路地址
     */
    routeAddress:string;
    /**
     * 订单状态
     */
    orderStatus:string;
    /**
     * 发货起始时间
     */
    startTime:string;
    /**
     * 发货结束时间
     */
    endTime:string;
    /**
     * 客服专员
     */
    customerServiceOfficerId: string;
    /**
     * 车长
     */
    carLength:string;
    /**
     * 合同号
     */
    contractId:string;
    /**
     * 合同状态
     */
    contractStatus:string;
    /**
     * 回单状态
     */
    receiptStatus:string;
    /**
     * 油卡状态
     */
    oilCardStatus:string;
    /**
     * 调度专员
     */
    dispatchOfficerId: string;
    /**
     * 发货地址
     */
    originAddress:string;
    /**
     * 送货地址
     */
    deliverAddress:string;
    /**
     * 油卡卡号
     */
    oilCardNumber:string;
    /**
     * 车牌号
     */
    carCode:string;
    /**
     * 承运商名称
     */
    carrierName:string;
    /**
     * 驾驶员号码
     */
    driverPhone:string;
    /**
     * 货已送达起始时间
     */
    deliveredStartTime:'';
    /**
     * 货已送达结束时间
     */
    deliveredEndTime:''
    
}

class IOrderDeliverController extends ListController<IOrderDeliverManagentViewModel,IOrderDeliverQueryTerms> {
    gridApi: uiGrid.IGridOptionsOf<carryOrderListResponse>;
    orderBy: number = 4;
    asc: boolean = false;

    /**
     * 单选
     */
    selectData:carryOrderListResponse;
    selectedId:string;

    skip:number = 0;


    constructor($scope:IOrderDeliverManagentViewModel, private orderService:IorderService, private employeeService:IEmployeeService, private valueService: IValueService,
     private $ngBootbox: BootboxService, private $state: angular.ui.IStateService,private routeService:routeService,private $location:ng.ILocationService,private exportService:IexportService){
        super($scope);
        this.init();
    }

    /**
     * 初始化
     */
    init():void{
        super.init();
    this.$scope.carLocation = true;

        this.$scope.queryTerms = {
            orderId:"",
            clientName: "",
            routeAddress: "",
            orderStatus: "",
            startTime: "",
            endTime: "",
            customerServiceOfficerId: "",
            carLength: "",
            contractId: "",
            contractStatus: "",
            receiptStatus: "",
            oilCardStatus: "",
            dispatchOfficerId: "",
            originAddress: "",
            deliverAddress: "",
            carCode: "",
            carrierName: "",
            oilCardNumber:'',
            driverPhone:'',
            //新增 货已送达起始时间 和 货已送达结束时间
            deliveredStartTime:'',
            deliveredEndTime:''
            
        };

        this.$scope.gridOptions = {
            multiSelect:false,//单选
            enableRowSelection: true,
            enableRowHeaderSelection: false,
            enableSelectAll: false,//全选禁用
            paginationPageSizes: [10, 20, 30],
            useExternalPagination: true,
            useExternalSorting: true,
            enableColumnResizing: true,
            columnDefs: [
                { displayName: "订单编号", field: 'orderId', cellTemplate: '<div  ng-repeat="item in row.entity.orderList"class="LTL-list">{{item.orderId}}</div>', enableColumnMenu: false, width: '8%' },
                { displayName: "客户单位", field: 'clientName', cellTemplate: '<div  ng-repeat="item in row.entity.orderList" class="LTL-list">{{item.clientName}}</div>', enableColumnMenu: false, width: '9%' },
                { displayName: "发货地址", field: 'startAddress', cellTemplate: '<div  ng-repeat="item in row.entity.orderList" class="LTL-list">{{item.startAddress}}</div>', enableColumnMenu: false, width: '9%' },
                { displayName: "送货地址", field: 'endAddress', cellTemplate: '<div  ng-repeat="item in row.entity.orderList" class="LTL-list">{{item.endAddress}}</div>', enableColumnMenu: false, width: '9%' },
                { displayName: "发货时间", field: 'shipTime', cellTemplate: '<div  ng-repeat="item in row.entity.orderList" class="LTL-list">{{item.shipTime}}</div>', enableColumnMenu: false,width:'7%' },
                { displayName: "订单状态", field: 'orderStatus', cellTemplate: '<div  ng-repeat="item in row.entity.orderList" class="LTL-list">{{item.orderStatus}}</div>', enableColumnMenu: false },
                { displayName: '回单状态', field: 'receiptStatus', cellTemplate: '<div  ng-repeat="item in row.entity.orderList" class="LTL-list">{{item.receiptStatus}}</div>', enableColumnMenu: false },
                { displayName: "客服专员", field: 'customerService', cellTemplate: '<div  ng-repeat="item in row.entity.orderList" class="LTL-list">{{item.customerService}}</div>', enableColumnMenu: false, enableSorting: false },
                { displayName: "调度专员", field: 'dispatcher', cellTemplate: '<div  ng-repeat="item in row.entity.orderList" class="LTL-list">{{item.dispatcher}}</div>', enableColumnMenu: false, enableSorting: false },
                { displayName: '合同号', field: 'contractNum', cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.contractNum}}</div>', enableColumnMenu: false },
                { displayName: '承运商名称', field: 'carrierName', cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.carrierName}}</div>', enableColumnMenu: false, enableSorting: false },
                { displayName: '承运车牌号', field: 'carCode', cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.carryCarCode}}</div>', enableColumnMenu: false },
                { displayName: "车长", field: 'carLength', cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.carryCarLength}}</div>', enableColumnMenu: false, },
                { displayName: '应付单价', field: 'receivablePrice', cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.receivablePrice}}</div>', enableColumnMenu: false, enableSorting: false },
                { displayName: '合同状态', field: 'contractStatus', cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.contractStatus}}</div>', enableColumnMenu: false },
                { displayName: '油卡状态', field: 'oilCardStatus', cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.oilCardStatus}}</div>', enableColumnMenu: false },
                {
                            displayName: '定位状态', field: 'locationStatus',
                            cellTemplate: '<div ng-if="row.entity.locationStatus == true ">'
                                        + '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">已开通</div>'
                                        + '</div>'
                                        + '<div ng-if="row.entity.locationStatus == false ">'
                                           + '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">未开通</div>'
                                           + '<div>'
                                           + '<div ng-if="row.entity.locationStatus == true " >'
                                           + '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">已开通</div>'
                                           + '<div>',
                            enableColumnMenu: false, enableSorting: false
                        },
            ],
            onRegisterApi: (gridApi) => {
                    if(window.localStorage.getItem(String(this.$state.current.url+'Page'))){
                        this.$scope.gridOptions.paginationCurrentPage=this.paginationOptions.currentPage;
                    };
                    
                    gridApi.pagination.on.paginationChanged(this.$scope,(skipSize,pageSize)=>{
                        this.paginationChanged(skipSize,pageSize,this.$state);
                    });
                    
                    gridApi.core.on.sortChanged(this.$scope, this.sortChange);
                    gridApi.selection.on.rowSelectionChanged(this.$scope, this.selectChange);
            }
        }

         $('#openStartTime').click(function () {
             $('#shipStartTime').datetimepicker('show');
         });
         $('#openEndTime').click(function () {
             $('#shipEndTime').datetimepicker('show');
         });
         
        $('#openDeliveredStart').click(function(){
            $('#deliveredStartTime').datetimepicker('show');
        })
        $('#openDeliveredEnd').click(function(){
            $('#deliveredEndTime').datetimepicker('show');
        })

        this.query();
        this.$scope.orderDetail = this.showOrderDetail;
        this.loadDispatchOfficerDropDown();
        this.loadOrderStatusDropDown();
        this.loadCustomerServiceDropDown();
        this.loadCarLengthDropDown();
        this.loadContractStatusDropDown();
        this.loadReceiptStatusDropDown();
        this.loadOilCCardStatusDropDown();

        this.$scope.location = this.location;
        this.$scope.track = this.track;

        /**
         * 北斗定位
         */
        this.$scope.BDNPL =  ()=> {
            var Sid = this.selectData;

            var orderL = Sid.orderList[0];

            var shipTime = orderL.shipTime;

            this.$state.go("app.car.BDNPLocation", { id: Sid.carId, shipTime: shipTime, carcode: Sid.carryCarCode, phone: Sid.driverPhone, realArrivalTime: Sid.realArrivalTime, shipAddress: orderL.startAddress, deliverAddress: orderL.endAddress });

        }
    }

    //新增：送达按钮点击时间  queryTerms.deliveredStartTime,queryTerms.deliveredEndTime
    exportFunc=(arg?:boolean)=>{
        if(arg){
            if(this.$scope.gridOptions.totalItems>30000){
                this.$ngBootbox.alert('导出数据不可超过3万条');
                return;
            }else{
                this.exportService.excelCarryOrderList(this.orderBy,this.asc,this.queryTerms.orderId,this.queryTerms.clientName,this.queryTerms.routeAddress,this.queryTerms.startTime,this.queryTerms.endTime,this.queryTerms.orderStatus,"","",this.queryTerms.originAddress,this.queryTerms.deliverAddress,this.queryTerms.carCode,this.queryTerms.contractId,this.queryTerms.contractStatus,this.queryTerms.receiptStatus,this.queryTerms.oilCardStatus,this.queryTerms.customerServiceOfficerId,this.queryTerms.dispatchOfficerId,this.queryTerms.carrierName,this.queryTerms.carLength,this.queryTerms.oilCardNumber,true,this.queryTerms.driverPhone,this.queryTerms.deliveredStartTime,this.queryTerms.deliveredEndTime);
            }
            
        }else{
            if(this.$scope.gridOptions.totalItems>30000){
                this.$ngBootbox.alert('导出数据不可超过3万条');
                return;
            }else{
                this.exportService.excelCarryOrderList(this.orderBy,this.asc,this.queryTerms.orderId,this.queryTerms.clientName,this.queryTerms.routeAddress,this.queryTerms.startTime,this.queryTerms.endTime,this.queryTerms.orderStatus,"","",this.queryTerms.originAddress,this.queryTerms.deliverAddress,this.queryTerms.carCode,this.queryTerms.contractId,this.queryTerms.contractStatus,this.queryTerms.receiptStatus,this.queryTerms.oilCardStatus,this.queryTerms.customerServiceOfficerId,this.queryTerms.dispatchOfficerId,this.queryTerms.carrierName,this.queryTerms.carLength,this.queryTerms.oilCardNumber,false,this.queryTerms.driverPhone,this.queryTerms.deliveredStartTime,this.queryTerms.deliveredEndTime);
            }          
        }
    }
    /**
     * 加载数据
     */
    loadData(queryTerms:IOrderDeliverQueryTerms,skip:number,count:number):void{
        // if(queryTerms.orderStatus == "" || queryTerms.orderStatus == undefined ){
        //     queryTerms.orderStatus = "3,4,5,6,7";
        // }
        this.orderService.carryOrderList(this.orderBy.toString(),this.asc,queryTerms.orderId,queryTerms.clientName,queryTerms.routeAddress,queryTerms.startTime,queryTerms.endTime,
        queryTerms.orderStatus,"","",queryTerms.originAddress,queryTerms.deliverAddress,queryTerms.carCode,queryTerms.contractId,queryTerms.contractStatus,queryTerms.receiptStatus,
        queryTerms.oilCardStatus,queryTerms.customerServiceOfficerId,"",queryTerms.dispatchOfficerId,queryTerms.carLength,queryTerms.carrierName,'',queryTerms.oilCardNumber,queryTerms.driverPhone,
        "",queryTerms.deliveredStartTime,queryTerms.deliveredEndTime,skip,count).then((result)=>{
            // this.$scope.gridOptions.totalItems = result.data.total;
            this.$scope.gridOptions.data = result.data.data;
            let gridHeight = 0;
            result.data.data.forEach((item,index)=>{
                gridHeight = gridHeight + item.orderList.length;
            });
            this.$scope.heightA = (gridHeight * 39)+96;
            if (skip == 0) {
                this.$scope.gridOptions.paginationCurrentPage = 1;
            }
            this.skip = skip;
            this.$scope.querying = false;
        }, error => {
            this.$scope.querying = false;
        });
    }

    //新增查询条件： queryTerms.deliveredStartTime,queryTerms.deliveredEndTime
    getListCount():void{
        this.orderService.carrierOrderCount(this.$scope.queryTerms.orderId,this.$scope.queryTerms.clientName,this.$scope.queryTerms.routeAddress,this.$scope.queryTerms.startTime,this.$scope.queryTerms.endTime,
        this.$scope.queryTerms.orderStatus,"","",this.$scope.queryTerms.originAddress,this.$scope.queryTerms.deliverAddress,this.$scope.queryTerms.carCode,this.$scope.queryTerms.contractId,this.$scope.queryTerms.contractStatus,this.$scope.queryTerms.receiptStatus,
        this.$scope.queryTerms.oilCardStatus,this.$scope.queryTerms.customerServiceOfficerId,"",this.$scope.queryTerms.dispatchOfficerId,this.$scope.queryTerms.carLength,this.$scope.queryTerms.carrierName,'',this.$scope.queryTerms.oilCardNumber,this.$scope.queryTerms.driverPhone,
        "",this.$scope.queryTerms.deliveredStartTime,this.$scope.queryTerms.deliveredEndTime).then(res=>{
            this.$scope.gridOptions.totalItems = res.data.extData;
        })
    }

    localHistory():void{
        super.localHistory(this.$state);
    }
    getHistory():void{
        super.getHistory(this.$state,this.$location)
    }


    /**
     * 排序事件触发
     */
    sortChange=(grid:  uiGrid.IGridInstanceOf<carryOrderListResponse>, sortColumns: Array<uiGrid.IGridColumnOf<carryOrderListResponse>>)=>{
        if (sortColumns.length == 0) {
            this.reload();
        } else {
            let sortItem = sortColumns[0];
            switch (sortItem.name) {
                case "orderId": {
                    this.orderBy = 1;
                } break;
                case "clientName": {
                    this.orderBy = 2;
                } break;
                case "startAddress": {
                    this.orderBy = 3;
                } break;
                case "endAddress": {
                    this.orderBy = 4;
                } break;
                case "shipTime": {
                    this.orderBy = 5;
                } break;
                case "orderStatus": {
                    this.orderBy = 6;
                } break;
                case "receiptStatus": {
                    this.orderBy = 7;
                } break;
                case "contractNum": {
                    this.orderBy = 8;
                } break;
                case "carCode": {
                    this.orderBy = 9;
                } break;
                case "carLength": {
                    this.orderBy = 10;
                } break;
                case "contractStatus": {
                    this.orderBy = 11;
                } break;
                case "oilCardStatus": {
                    this.orderBy = 12;
                } break;
            }
            this.asc = sortItem.sort.direction == "asc";
            this.reload();
       }
    }

    /**
     * 调度专员下拉
     */
    loadDispatchOfficerDropDown():void{
        this.employeeService.getbytype(CommissionerType.Dispatch.toString(),0,-1).then(result => {
            this.$scope.dispatchOfficerDropDown = result.data.data;
        });
    }

    /**
     * 订单状态下拉
     */
    loadOrderStatusDropDown():void{
        let OrderStatus = this.valueService.getOrderStatusList().data;
        OrderStatus.splice(0,2);
        OrderStatus.splice(5,1);
        this.$scope.orderStatusDropDown = OrderStatus;
    }
    
    /**
     * 客服专员下拉
     */
    loadCustomerServiceDropDown():void{
        this.employeeService.getbytype(CommissionerType.CustomerService.toString(),0,-1).then(result => {
            this.$scope.customerServiceDropDown = result.data.data;
        });
    }
    
    /**
     * 车长下拉
     */
    loadCarLengthDropDown():void{
        this.$scope.carLengthDropDown = this.valueService.getCarLengthList().data;
    }
    
    /**
     * 合同状态下拉
     */
    loadContractStatusDropDown():void{
        this.$scope.contractStatusDropDown = this.valueService.getContractStatusList().data;
    }
    
    /**
     * 回单状态下拉
     */
    loadReceiptStatusDropDown():void{
        this.$scope.receiptStatusDropDown = this.valueService.getReceiptStatusList().data;
    }
    
    /**
     * 油卡状态下拉
     */
    loadOilCCardStatusDropDown():void{
        this.$scope.oilCCardStatusDropDown = this.valueService.getOilCCardStatusList().data;
    }
    
    /**
     * 单选定位
     */
    selectChange=(row:uiGrid.IGridRowOf<carryOrderListResponse>)=> {
        if (row.isSelected) {
            this.selectData = row.entity;
            this.$scope.carLocation = false
        } else {
            this.selectData = null;
            this.$scope.carLocation = true;
        }
        
    };

    /**
     * 查看详情
     */
    showOrderDetail=()=>{
        if(!this.selectData){
            this.$ngBootbox.alert("请选择一项");
            return;
        }
        if(this.selectData.orderList.length > 1 ){
            this.$state.go('app.order.LTL_detail',{ id:this.selectData.id ,  name:'Manage', type:this.selectData.orderList[0].orderStatus, skip:this.skip ,isReverse:false });
        }else{
            this.$state.go('app.order.invoice_detail',{ id:this.selectData.id ,  name:'Manage', type:this.selectData.orderList[0].orderStatus, skip:this.skip ,isReverse:false});
        };
    };

      /**
       * 定位
       */
      location=()=>{
          this.orderService.carryOrder(this.selectData.id).then((res)=>{
            let carId = res.data.carId;
            let carCode = res.data.carCode;
            let phoneNumber = res.data.driverPhone;
            let shipAddressL=this.selectData.orderList[0].startAddress;
            let deliverAddressL=this.selectData.orderList[0].endAddress;
            this.$state.go("app.car.carLocation", { id: carId, carcode: carCode, phone: phoneNumber, shipAddress: shipAddressL, deliverAddress: deliverAddressL })
          });
      }

      /**
       * 定位轨迹点
       */
      track=()=>{
          if(this.selectData.orderList[0].orderStatus!="已发货"&&this.selectData.orderList[0].orderStatus!="货已送达"){
              this.$ngBootbox.alert("只有已发货或货已送达才可以定位轨迹点")
              return
          }
          let carId = this.selectData.carId;
          let shipTime = this.selectData.orderList[0].shipTime;
          let carryCarCode = this.selectData.carryCarCode;
          let driverPhone = this.selectData.driverPhone;
          let realArrivalTime = this.selectData.realArrivalTime;
          let startAddress = this.selectData.orderList[0].startAddress;
          let endAddress = this.selectData.orderList[0].endAddress;
          this.$state.go("app.car.carStrackController", { id: carId, shipTime: shipTime, carcode: carryCarCode, phone: driverPhone, realArrivalTime: realArrivalTime, shipAddress: startAddress, deliverAddress: endAddress });
      }
      

}

angular.module("tms").controller("orderDeliverManagentController", ["$scope", "orderService", "employeeService","valueService", "$ngBootbox",  "$state", "routeService","$location","exportService",IOrderDeliverController]);